#[cfg(not(target_arch="wasm32"))]
pub(crate) use egui_dy::eframe;

#[cfg(target_arch="wasm32")]
use wasm_bindgen::prelude::*;

pub(crate) use eframe::egui;
use egui::{FontId, FontFamily, Layout, Align, Ui, Context};

mod math;
mod ui_utils;
mod math_ui; use math_ui::{MathUiSys, init_fonts};
mod history;
mod char_utils; use char_utils::str_to_italic;

#[cfg(not(target_arch="wasm32"))]
pub fn run_native() {
    let native_options = eframe::NativeOptions::default();
    eframe::run_native(
        "mathcc", 
        native_options, 
        Box::new(|cc| Box::new(App::new(cc)))
    ).unwrap();
}

#[cfg(target_arch="wasm32")]
#[wasm_bindgen]
pub async fn run_web(canvas_id: &str) -> Result<(), wasm_bindgen::JsValue> {
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));
    eframe::WebRunner::new().start(
        canvas_id,
        eframe::WebOptions::default(),
        Box::new(|cc| Box::new(App::new(cc))),
    ).await
}

struct App {
    // once_printer: utils::OncePrinter,
    math_ui_list: Vec<MathUiSys>,
    current_tag: usize,
}

impl App {
    fn new(cc: &eframe::CreationContext<'_>) -> Self {
        init_fonts(&cc.egui_ctx);
        math::test();
        Self {
            math_ui_list: vec![MathUiSys::new()],
            current_tag: 0,
        }
    }
}

impl eframe::App for App {
    fn update(&mut self, ctx: &Context, _: &mut eframe::Frame) {
        egui::TopBottomPanel::top("Top Panel").show(ctx, Self::render_top_panel);
        egui::CentralPanel::default().show(ctx, |ui| {
            self.math_ui_list[self.current_tag].update(ctx, ui);
        });
        // egui::Window::new("test window").show(ctx, |ui| {
        // });
    }
}

impl App {
    fn render_top_panel(ui: &mut Ui) {
        ui.horizontal(|ui| {
            ui.scope(|ui| {
                ui.style_mut().override_font_id = Some(
                    FontId::new(17.0, FontFamily::Name("math".into()))
                );
                ui.label(str_to_italic("mathcc"));
            });
            ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                egui::widgets::global_dark_light_mode_switch(ui);
            });
        });
    }
}